import { UploadFile } from "antd/lib/upload/interface";
import { parseFileToSheetJson } from "./fileToModelUtil";
import Machine from "./Machine";
import { addMachine, addWorker, getDepartment, getMachine } from "./store";
import Worker from "./Worker";

export function parseWorkerByFileList(workerFileList: UploadFile[]): Promise<void> {
    return new Promise((resolve, reject) => {
        const promiseList: Promise<void>[] = [];
        workerFileList.forEach(workerFile => {
            if (workerFile.originFileObj !== undefined) {
                promiseList.push(parseWorkerByFile(workerFile));
            }
        });
        Promise.all(promiseList).then(() => {
            resolve();
        }, reject);
    });
}

export function parseWorkerByFile(workerFile: UploadFile): Promise<void> {
    return new Promise((resolve, reject) => {
        if (workerFile.originFileObj === undefined) {
            reject(`《${workerFile.name}》是无效的考勤记录文件，请严格按照格式要求上传数据和格式正确的文件。`);
        } else {
            parseFileToSheetJson(workerFile, '员工信息').then(workerJson => {
                if (workerJson.length > 1) {
                    for (let i = 1, limit = workerJson.length; i < limit; i++) {
                        const workerInfo = workerJson[i];
                        let [machineId, id, name, departmentId] = workerInfo;
                        machineId = String(machineId);
                        id = String(id);
                        name = String(name);
                        departmentId = String(departmentId);
                        if (machineId.length > 0 && id.length > 0 && name.length > 0 && departmentId.length > 0) {
                            let machine = getMachine(machineId);
                            if (machine === undefined) {
                                machine = new Machine({
                                    id: machineId
                                });
                                addMachine(machine);
                            }
                            const department = getDepartment(departmentId) || getDepartment('default');
                            if (machine !== undefined && department !== undefined) {
                                addWorker(new Worker({
                                    machine,
                                    id,
                                    name,
                                    department
                                }));
                            }
                        }
                    }
                    resolve();
                }
            }, reject);
        }
    });
}